import axios from 'axios'
import { Message } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
import router from '@/router'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = 'bearer ' + getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    if (response.status === 401) {
      store.dispatch('user/resetToken').then(() => {
        router.push({
          path: '/login'
        })
      })
      return null
    }

    if (response.status === 500) {
      Message({
        message: '服务器错误',
        type: 'error',
        duration: 2000
      })

      return
    }

    if (response.status === 403) {
      router.push({
        path: '/403'
      })
      return null
    }

    const res = response.data
    if (res.success !== true) {
      return res
    } else {
      return res
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 2 * 1000
    })
    if (error.response.status === 401) {
      store.dispatch('user/resetToken').then(() => {
        router.push({
          path: '/login'
        })
      })

      return
    }
    if (error.response.status === 500) {
      Message({
        message: error.message,
        type: 'error',
        duration: 2 * 1000
      })

      return
    }
    if (error.response.status === 403) {
      router.push({
        path: '/403'
      })
      return
    }
    return Promise.reject(error)
  }
)

export default service
